package com.code.zg.rxapplication.bean;

import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;

/**
 * Created by zhanggang on 2017/8/25.
 */

public class AppInfoRich implements Comparable<Object> {
    public  String mName;
    public Context context;
    public ResolveInfo resolveInfo;
    public ComponentName componentName;
    public PackageInfo packageInfo;
    public Drawable icon;

    public AppInfoRich(Context context, ResolveInfo resolveInfo) {
        this.context = context;
        this.resolveInfo = resolveInfo;
        componentName=new ComponentName(getPackageName(),getActivityName());
        try {
            packageInfo=context.getPackageManager().getPackageInfo(resolveInfo.activityInfo.packageName,0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    public String getActivityName(){
        return resolveInfo.activityInfo.name;
    }
    public String getPackageName(){
        return resolveInfo.activityInfo.packageName;
    }
    public ComponentName getComponentName(){
        return componentName;
    }
    public PackageInfo getPackageInfo(){
        return packageInfo;
    }
    public Drawable getIcon(){
        if(icon==null){
            icon=resolveInfo.loadIcon(context.getPackageManager());
        }
        return icon;
    }
    public long getLastUpdateTime(){
        return getPackageInfo().lastUpdateTime;
    }
    public String getmName(){
        if(mName!=null){
            return mName;
        }else{
            return getNameFromResolveInfo(resolveInfo);
        }
    }

    public String getNameFromResolveInfo(ResolveInfo resolveInfo) {
        String name = resolveInfo.resolvePackageName;
        if(resolveInfo.activityInfo!=null){
            try {
                Resources res = context.getPackageManager().getResourcesForApplication(getPackageName());
//                Resources engRes=getEnglishRes(res);
                if(resolveInfo.activityInfo.labelRes!=0){
                     name = res.getString(resolveInfo.activityInfo.labelRes);
                }else{
                    name=resolveInfo.activityInfo.applicationInfo.loadLabel(context.getPackageManager()).toString();
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return name;
    }

//    private Resources getEnglishRes(Resources res) {
//        return
//    }

    @Override
    public int compareTo(@NonNull Object o) {
        AppInfoRich appInfoRich= (AppInfoRich) o;
        return appInfoRich.mName.compareTo(((AppInfoRich) o).mName);
    }
}
